import { useCallback, useMemo } from 'react';
import { debounce } from 'lodash';
import { TitleConfig } from '../types';

/**
 * 标题配置Hook，封装标题相关配置逻辑
 * @param title 当前标题配置
 * @param onChange 配置变更回调
 * @returns 标题配置相关操作方法
 */
export const useTitleConfig = (
    title: TitleConfig,
    onChange: (title: TitleConfig) => void
) => {
    // 基础属性变更
    const handleChange = useCallback((key: keyof TitleConfig, value: any) => {
        onChange({
            ...title,
            [key]: value
        });
    }, [title, onChange]);

    // 主标题样式变更
    const handleTextStyleChange = useCallback((key: string, value: any) => {
        onChange({
            ...title,
            textStyle: {
                ...title.textStyle,
                [key]: value
            }
        });
    }, [title, onChange]);

    // 副标题样式变更
    const handleSubtextStyleChange = useCallback((key: string, value: any) => {
        onChange({
            ...title,
            subtextStyle: {
                ...title.subtextStyle,
                [key]: value
            }
        });
    }, [title, onChange]);

    // 位置变更
    const handlePositionChange = useCallback((key: string, value: any) => {
        onChange({
            ...title,
            position: {
                ...title.position,
                [key]: value
            }
        });
    }, [title, onChange]);

    // 防抖处理函数
    const debouncedTextStyleChange = useMemo(
        () => debounce((key: string, value: any) => {
            handleTextStyleChange(key, value);
        }, 100),
        [handleTextStyleChange]
    );

    const debouncedSubtextStyleChange = useMemo(
        () => debounce((key: string, value: any) => {
            handleSubtextStyleChange(key, value);
        }, 100),
        [handleSubtextStyleChange]
    );

    const debouncedPositionChange = useMemo(
        () => debounce((key: string, value: any) => {
            handlePositionChange(key, value);
        }, 100),
        [handlePositionChange]
    );

    const debouncedHandleChange = useMemo(
        () => debounce((key: keyof TitleConfig, value: any) => {
            handleChange(key, value);
        }, 100),
        [handleChange]
    );

    // 处理内边距数组形式的输入
    const handlePaddingChange = useCallback((index: number, value: number) => {
        let newPadding: number[] = [];

        if (Array.isArray(title.padding)) {
            newPadding = [...title.padding];
        } else if (typeof title.padding === 'number') {
            newPadding = [title.padding, title.padding, title.padding, title.padding];
        } else {
            newPadding = [5, 5, 5, 5]; // 默认值
        }

        newPadding[index] = value;
        handleChange('padding', newPadding);
    }, [title.padding, handleChange]);

    // 颜色解析函数
    const parseRgba = useCallback((rgba: string): { r: number, g: number, b: number, a: number } => {
        const defaultColor = { r: 0, g: 0, b: 0, a: 0.3 };
        if (!rgba) return defaultColor;

        try {
            if (rgba.startsWith('#')) {
                // 处理十六进制颜色
                const hex = rgba.substring(1);
                if (hex.length === 6) {
                    return {
                        r: parseInt(hex.slice(0, 2), 16),
                        g: parseInt(hex.slice(2, 4), 16),
                        b: parseInt(hex.slice(4, 6), 16),
                        a: 1
                    };
                }
            } else if (rgba.startsWith('rgba')) {
                // 处理rgba颜色
                const matches = rgba.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)/);
                if (matches && matches.length === 5) {
                    return {
                        r: parseInt(matches[1], 10),
                        g: parseInt(matches[2], 10),
                        b: parseInt(matches[3], 10),
                        a: parseFloat(matches[4])
                    };
                }
            }
        } catch (e) {
            console.error('Error parsing color', e);
        }

        return defaultColor;
    }, []);

    // RGB转十六进制
    const rgbToHex = useCallback((r: number, g: number, b: number): string => {
        try {
            return '#' + [r, g, b].map(x => {
                const hex = Math.max(0, Math.min(255, Math.round(x))).toString(16);
                return hex.length === 1 ? '0' + hex : hex;
            }).join('');
        } catch (e) {
            console.error('Error converting color to hex', e);
            return '#000000';
        }
    }, []);

    // 阴影颜色相关
    const shadowHexColor = useMemo(() => {
        if (!title.shadowColor) return '#000000';
        try {
            if (title.shadowColor.startsWith('rgba')) {
                const { r, g, b } = parseRgba(title.shadowColor);
                return rgbToHex(r, g, b);
            }
            return title.shadowColor;
        } catch (e) {
            return '#000000';
        }
    }, [title.shadowColor, parseRgba, rgbToHex]);

    const shadowAlpha = useMemo(() => {
        if (!title.shadowColor) return 0.3;
        try {
            if (title.shadowColor.startsWith('rgba')) {
                return parseRgba(title.shadowColor).a;
            }
            return 1;
        } catch (e) {
            return 0.3;
        }
    }, [title.shadowColor, parseRgba]);

    // 处理阴影颜色变更
    const handleShadowColorChange = useCallback((hexColor: string) => {
        try {
            const r = parseInt(hexColor.slice(1, 3), 16);
            const g = parseInt(hexColor.slice(3, 5), 16);
            const b = parseInt(hexColor.slice(5, 7), 16);
            debouncedHandleChange('shadowColor', `rgba(${r}, ${g}, ${b}, ${shadowAlpha})`);
        } catch (e) {
            console.error('Error handling color change', e);
        }
    }, [shadowAlpha, debouncedHandleChange]);

    // 处理阴影透明度变更
    const handleShadowAlphaChange = useCallback((value: number | null) => {
        try {
            if (value === null) return;
            const { r, g, b } = parseRgba(title.shadowColor || 'rgba(0,0,0,0.3)');
            debouncedHandleChange('shadowColor', `rgba(${r}, ${g}, ${b}, ${value})`);
        } catch (e) {
            console.error('Error handling opacity change', e);
        }
    }, [title.shadowColor, parseRgba, debouncedHandleChange]);

    return {
        handleChange,
        handleTextStyleChange,
        handleSubtextStyleChange,
        handlePositionChange,
        debouncedTextStyleChange,
        debouncedSubtextStyleChange,
        debouncedPositionChange,
        debouncedHandleChange,
        handlePaddingChange,
        parseRgba,
        rgbToHex,
        shadowHexColor,
        shadowAlpha,
        handleShadowColorChange,
        handleShadowAlphaChange
    };
}; 